<template>
    <div id="teacher">
        <!-- 卡片视图区域 -->
        <el-card>
            <el-row :gutter="20">
                <el-col :span="8">
                    <!-- 搜索与添加区域 -->
                    <el-input placeholder="请输入教师姓名或ID"
                        v-model="queryInfo.query"
                        clearable>
                        <template #append>
                            <el-button @click="handleSearch">
                                <el-icon>
                                    <search />
                                </el-icon>
                            </el-button>
                        </template>
                    </el-input>
                </el-col>
                <el-col :span="4">
                    <el-button type="primary"
                        @click="addDialogVisible = true">添加教师</el-button>
                </el-col>
            </el-row>
            <!-- 教师列表区域 -->
            <el-table :data="teacherList"
                border
                stripe>
                <el-table-column type="index"></el-table-column>
                <el-table-column label="教师ID"
                    prop="teacherId"></el-table-column>
                <el-table-column label="教师姓名"
                    prop="teacherName"
                    width="120px"></el-table-column>
                <el-table-column label="联系电话"
                    prop="teacherPhone"
                    width="150px"></el-table-column>
                <el-table-column label="所属院系"
                    width="150">
                    <template #default="scope">
                        {{ departmentMap[scope.row.departmentId] || '未知院系' }}
                    </template>
                </el-table-column>
                <el-table-column label="职称"
                    prop="teacherTitle"
                    width="100px"></el-table-column>
                <el-table-column label="操作"
                    width="200px">
                    <template v-slot="scope">
                        <!-- 修改按钮 -->
                        <el-button type="primary"
                            @click="showEditDialog(scope.row.teacherId)">
                            <el-icon>
                                <edit />
                            </el-icon>
                        </el-button>
                        <!-- 删除 -->
                        <el-button type="danger"
                            @click="handleDelete(scope.row.teacherId)">
                            <el-icon>
                                <delete />
                            </el-icon>
                        </el-button>
                    </template>
                </el-table-column>
            </el-table>

            <!-- 分页区域 -->
            <el-pagination v-model:current-page="queryInfo.pagenum"
                v-model:page-size="queryInfo.pagesize"
                :total="total"
                :page-sizes="[10, 20, 50, 100]"
                layout="total, sizes, prev, pager, next, jumper"
                @size-change="handleSizeChange"
                @current-change="handleCurrentChange" />
        </el-card>

        <!-- 添加教师对话框 (预留，功能暂未实现) -->
        <el-dialog v-model="addDialogVisible"
            title="添加教师"
            width="50%">
            <el-form :model="addForm"
                :rules="addFormRules"
                ref="addFormRef"
                label-width="80px">
                <el-form-item label="教师ID"
                    prop="teacherId">
                    <el-input v-model="addForm.teacherId"
                        autocomplete="off" />
                </el-form-item>
                <el-form-item label="教师姓名"
                    prop="teacherName">
                    <el-input v-model="addForm.teacherName"
                        autocomplete="off" />
                </el-form-item>
                <el-form-item label="所属院系"
                    prop="departmentId">
                    <el-select v-model="addForm.departmentId"
                        placeholder="请选择所属院系"
                        :options="departmentOptions"
                        filterable
                        clearable>
                        <el-option v-for="item in departmentOptions"
                            :key="item.value"
                            :label="item.label"
                            :value="item.value" />
                    </el-select>
                </el-form-item>
                <el-form-item label="联系电话"
                    prop="teacherPhone">
                    <el-input v-model="addForm.teacherPhone"
                        autocomplete="off" />
                </el-form-item>
                <el-form-item label="职称"
                    prop="teacherTitle">
                    <el-input v-model="addForm.teacherTitle"
                        autocomplete="off" />
                </el-form-item>
            </el-form>
            <template #footer>
                <el-button @click="addDialogVisible = false">取消</el-button>
                <el-button type="primary"
                    @click="submitAddForm">确定</el-button>
            </template>
        </el-dialog>

        <!-- 修改教师对话框 (预留，功能暂未实现) -->
        <el-dialog v-model="editDialogVisible"
            title="修改教师信息"
            width="50%">
            <el-form :model="editForm"
                ref="editFormRef"
                label-width="80px">
                <el-form-item label="教师ID">
                    <el-input v-model="editForm.teacherId"
                        disabled /> <!-- 不可修改 -->
                </el-form-item>
                <el-form-item label="教师姓名"
                    prop="teacherName">
                    <el-input v-model="editForm.teacherName" />
                </el-form-item>
                <el-form-item label="所属院系"
                    prop="departmentId">
                    <el-select v-model="editForm.departmentId"
                        :options="departmentOptions"
                        filterable
                        clearable>
                        <el-option v-for="item in departmentOptions"
                            :key="item.value"
                            :label="item.label"
                            :value="item.value" />
                    </el-select>
                </el-form-item>
                <el-form-item label="联系电话"
                    prop="teacherPhone">
                    <el-input v-model="editForm.teacherPhone" />
                </el-form-item>
                <el-form-item label="职称"
                    prop="teacherTitle">
                    <el-input v-model="editForm.teacherTitle" />
                </el-form-item>
            </el-form>
            <template #footer>
                <el-button @click="editDialogVisible = false">取消</el-button>
                <el-button type="primary"
                    @click="submitEditForm">保存修改</el-button>
            </template>
        </el-dialog>
    </div>
</template>

<style scoped></style>

<script>
import {
    getTeacherList,
    getDepartmentList,
    getTeacherDetail,
    addTeacher, // 确保添加教师的方法已导入
    updateTeacher,
    deleteTeacher
} from '@/api/teacher';

export default {
    data() {
        return {
            // 查询参数
            queryInfo: {
                pageNum: 1,       // 当前页码
                pageSize: 10,     // 每页显示数量
                query: '',        // 查询关键词
                orderBy: 0        // 排序方式(后端默认0)
            },

            // 教师列表数据
            teacherList: [],
            // 院系列表数据
            departmentList: [],
            // 院系ID到名称的映射
            departmentMap: {},
            // 总数据条数
            total: 0,
            // 控制对话框显示与隐藏
            addDialogVisible: false,
            editDialogVisible: false,
            // 添加教师表单数据
            addForm: {
                teacherId: '',
                teacherName: '',
                departmentId: '',
                teacherPhone: '',
                teacherTitle: ''
            },
            // 添加表单验证规则
            addFormRules: {
                teacherId: [{ required: true, message: "请输入教师ID", trigger: "blur" }],
                teacherName: [{ required: true, message: "请输入教师姓名", trigger: "blur" }],
                departmentId: [{ required: true, message: "请选择所属院系", trigger: "change" }],
                teacherPhone: [{ required: true, message: "请输入联系电话", trigger: "blur" }],
                teacherTitle: [{ required: true, message: "请输入职称", trigger: "blur" }]
            },
            // 编辑教师表单数据
            editForm: {
                teacherId: '',
                teacherName: '',
                departmentId: '',
                teacherPhone: '',
                teacherTitle: ''
            },
            // 院系下拉选项
            departmentOptions: []
        };
    },
    created() {
        this.getTeacherList();
        this.fetchDepartments();
    },
    methods: {
        // 获取教师列表
        async getTeacherList() {
            try {
                const res = await getTeacherList(this.queryInfo);
                console.log(res);

                // 假设后端响应结构为 { code: 200, data: { list: [], total: 0 } }
                if (res.code === 200) {
                    this.teacherList = res.data.list || [];
                    this.total = res.data.total || 0;
                } else {
                    this.$message.error(res.message || '获取教师列表失败');
                }
            } catch (error) {
                console.error('获取教师列表失败:', error);
                this.$message.error('获取教师列表失败，请稍后再试');
            }
        },

        // 获取院系列表
        async fetchDepartments() {
            try {
                // 传递分页参数
                const params = {
                    pageNum: this.queryInfo.pageNum,
                    pageSize: this.queryInfo.pageSize,
                    orderBy: this.queryInfo.orderBy
                };

                const res = await getDepartmentList(this.queryInfo.pageNum, this.queryInfo.pageSize, this.queryInfo.orderBy, {});

                // 假设院系列表响应结构与教师列表类似
                if (res.code === 200) {
                    this.departmentList = res.data.list || [];
                    this.departmentMap = this.departmentList.reduce((map, item) => {
                        map[item.departmentId] = item.departmentName;
                        return map;
                    }, {});
                    this.departmentOptions = this.departmentList.map(item => ({
                        value: item.departmentId,
                        label: item.departmentName
                    }));
                } else {
                    this.$message.error(res.message || '获取院系列表失败');
                }
            } catch (error) {
                console.error('获取院系列表失败:', error);
                this.$message.error('获取院系列表失败，请稍后再试');
            }
        },

        // 显示编辑对话框 (完善后的版本)
        async showEditDialog(teacherId) {
            try {
                const res = await getTeacherDetail(teacherId);
                if (res.code === 200) {
                    this.editForm = res.data;
                    this.editDialogVisible = true;
                } else {
                    this.$message.error(res.message || '获取教师详情失败');
                }
            } catch (error) {
                console.error('获取教师详情失败:', error);
                this.$message.error('获取教师详情失败，请稍后再试');
            }
        },

        // 提交添加表单 (完善后的版本)
        async submitAddForm() {
            this.$refs.addFormRef.validate(async (valid) => {
                if (valid) {
                    try {
                        console.log(this.addForm);
                        const res = await addTeacher(this.addForm);


                        if (res.code === 200) {

                            this.$message.success('添加教师成功');
                            this.addDialogVisible = false;
                            this.getTeacherList();
                            this.$nextTick(() => {
                                this.$refs.addFormRef.resetFields();
                            });
                        } else {
                            this.$message.error(res.message || '添加教师失败');
                        }
                    } catch (error) {
                        console.error('添加教师失败:', error);
                        this.$message.error('添加教师失败，请稍后再试');
                    }
                }
            });
        },

        // 提交编辑表单 (完善后的版本)
        async submitEditForm() {
            this.$refs.editFormRef.validate(async (valid) => {
                if (valid) {
                    try {
                        const res = await updateTeacher(this.editForm);
                        if (res.code === 200) {
                            this.$message.success('修改教师成功');
                            this.editDialogVisible = false;
                            this.getTeacherList();
                        } else {
                            this.$message.error(res.message || '修改教师失败');
                        }
                    } catch (error) {
                        console.error('修改教师失败:', error);
                        this.$message.error('修改教师失败，请稍后再试');
                    }
                }
            });
        },

        // 处理删除 (完善后的版本)
        async handleDelete(teacherId) {
            try {
                const confirm = await this.$confirm(
                    '确认删除该教师? 此操作不可恢复',
                    '提示',
                    {
                        confirmButtonText: '确认',
                        cancelButtonText: '取消',
                        type: 'warning'
                    }
                );
                if (confirm === 'confirm') {
                    const res = await deleteTeacher(teacherId);
                    if (res.code === 200) {
                        this.$message.success('删除教师成功');
                        this.getTeacherList();
                    } else {
                        this.$message.error(res.message || '删除教师失败');
                    }
                }
            } catch (error) {
                console.error('删除教师失败:', error);
                this.$message.error('删除教师失败，请稍后再试');
            }
        }
    }
};
</script>